package yu.vert.ProducerConsume;

import java.util.LinkedList;
import java.util.List;

/**
 * 简单的消费生产者模型
 */
public class TestMain {

    private int MAX_SIZE = 100;
    private List<Object> list = new LinkedList<>();

    public void producer(String producer) {
        synchronized (list) {
            while (list.size() == MAX_SIZE) {
                System.out.println("仓库已满，【"+producer+"】： 暂时不能执行消费任务!");
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add(producer);
            System.out.println("【"+producer+"】：生产了一个产品\t【现仓储量为】:" + list.size());
            list.notifyAll();
        }
    }

    public void consume(String consume) {

        synchronized (list) {
            while (list.size() == 0) {
                System.out.println("仓库已空，【"+consume+"】： 暂时不能执行消费任务!");
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.remove(list.get(0));
            System.out.println("【"+consume+"】：消费了一个产品\t【现仓储量为】:" + list.size());
            list.notifyAll();
        }

    }

    public static void main(String[] args) {
        TestMain testMain = new TestMain();
        for (int i = 0; i < 6; i ++) {
            int intl = i;
            new Thread(() ->  testMain.producer(String.format("生产者%d:", intl))).start();
        }

        for(int i=1;i<8;i++)
        {
            int finalI = i;
            new Thread(()-> testMain.consume(String.format("消费者%d:", finalI))).start();
        }
    }

}
